package com.rzico.sbl.ui.manager

import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityBarrelHandleBinding
import com.rzico.sbl.model.HandleData
import com.rzico.sbl.other.*
import com.rzico.sbl.ui.order.OrderDetailActivity
import com.rzico.sbl.viewmodel.MasterViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.getTimeString
import com.xinnuo.common.helper.hideSoftInput
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.showTimeRangeDialog
import com.xinnuo.slimadapter.SlimAdapter
import org.json.JSONObject

class BarrelHandleActivity : BaseActivity(R.layout.activity_barrel_handle) {

    private val mBinding by lazy { ActivityBarrelHandleBinding.bind(getRootView()) }

    private var mKeyWord = ""
    private var mBeginDate = getFirstDate()
    private var mEndDate = getEndDate()

    override fun getViewModel() = get<MasterViewModel>()

    override fun initData() {
        setToolbarVisibility(isVisible = false)

        initLayout()
        initSearch()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData(pageNum)
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                emptyLayout.also {
                    it.emptyHint.text = "暂无相关押桶信息！"
                }

                recycleList.also { layout ->
                    layout.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = { getData(0) },
                        onLoad = {
                            isLoadingMore
                                .conditionFalse {
                                    isLoadingMore = true
                                    getData(pageNum)
                                }
                        }
                    )

                    layout.addItemDecoration(SpaceTBDecoration(hasHeader = false))

                    mAdapter = SlimAdapter.creator()
                        .register<HandleData>(R.layout.item_barrel_handle) { jector, bean, _ ->
                            jector.apply {
                                text(
                                    R.id.item_handle_time,
                                    when (bean.method) {
                                        "mortgage" -> "操作时间: ${bean.createDate.getTimeString()}"
                                        else -> "购买时间: ${bean.createDate.getTimeString()}"
                                    }
                                )
                                text(
                                    R.id.item_handle_title,
                                    "${bean.consignee}  ${bean.phone}"
                                )
                                text(R.id.item_handle_name, bean.name)
                                text(R.id.item_handle_count, bean.subQuantity)
                                text(R.id.item_handle_price, bean.subPrice.formatDecimal())
                                text(R.id.item_handle_admin, bean.adminName.orEmpty())

                                getView<View>(R.id.item_handle_admin_ll)
                                    .isGone = bean.adminName.isNullOrEmpty()

                                with<ImageView>(R.id.item_handle_img) {
                                    it.loadImage(bean.logo)
                                }

                                with<TextView>(R.id.item_handle_type) { view ->
                                    view.text = bean.methodDescr

                                    when (bean.method) {
                                        "order" -> {
                                            if (bean.status == "completed") {
                                                view.setTextColor(getColorEx(R.color.colorAccent))
                                            } else {
                                                view.text = "${bean.methodDescr}(处理中)"
                                                view.setTextColor(getColorEx(R.color.red))
                                            }
                                        }
                                        else -> view.setTextColor(getColorEx(R.color.colorAccent))
                                    }
                                }

                                with<TextView>(R.id.item_handle_hint) {
                                    it.text = when (bean.method) {
                                        "mortgage" -> "操作人："
                                        else -> "配送人："
                                    }
                                }

                                clicked {
                                    bean.orderSn
                                        .notEmpty {
                                            startActivityEx<OrderDetailActivity>("orderSn" to this)
                                        }
                                }
                            }
                        }
                        .attachTo(layout)
                }
            }
    }

    private fun initSearch() {
        mBinding
            .searchLayout
            .apply {
                searchEdit.hint = "请输入姓名、手机号"
                searchEdit.doOnTextChanged { text, _, _, _ ->
                    text?.let {
                        searchClose.isGone = it.isEmpty()

                        if (it.isEmpty() && mKeyWord.isNotEmpty()) {
                            mKeyWord = ""
                            updateList()
                        }
                    }
                }

                searchEdit.setOnEditorActionListener { _, actionId, _ ->
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        hideSoftInput() //隐藏软键盘

                        if (searchEdit.text.isBlank()) {
                            showToast("请输入会员姓名或手机号")
                        } else {
                            mKeyWord = searchEdit.textTrim
                            updateList()
                        }
                    }
                    return@setOnEditorActionListener false
                }

                searchClose.oneClick { searchEdit.setText("") }
                searchHint.oneClick {
                    if (searchEdit.text.isBlank()) {
                        showToast("请输入姓名、手机号")
                    } else {
                        mKeyWord = searchEdit.textTrim
                        updateList()
                    }
                }
            }

        getViewModel()
            .mHandleEvent
            .observe(this) {
                val obj = JSONObject(it).optJSONObject("data") ?: JSONObject()

                mBinding.apply {
                    handleCount.text = obj.optNotEmpty("subQuantity", "0")
                    handleMoney.text = obj.optNotNull("subPrice").formatDecimal()
                }
            }
    }

    override fun initListener() {
        mBinding
            .handleTime
            .apply {
                getViewModel().mUncheckTimeList[3].isChecked = true
                timeHint.text = getViewModel().mUncheckTimeList[3].hint

                timeLayout.oneClick {
                    getViewModel()
                        .showDropTimeFilter(
                            getIContext(),
                            timeHint,
                            timeHintArrow,
                            timeLayout,
                            getViewModel().mUncheckTimeList
                        ) { bean ->

                            if (bean.id != "7")
                                getViewModel()
                                    .mUncheckTimeList
                                    .last()
                                    .name = "自定义时间"

                            when (bean.id) {
                                "1" -> {
                                    mBeginDate = getTodayDate()
                                    mEndDate = getTodayDate()

                                    updateList()
                                }
                                "2" -> {
                                    mBeginDate = getBeforeDate()
                                    mEndDate = getBeforeDate()

                                    updateList()
                                }
                                "3" -> {
                                    mBeginDate = getMondayDate()
                                    mEndDate = getSundayDate()

                                    updateList()
                                }
                                "4" -> {
                                    mBeginDate = getFirstDate()
                                    mEndDate = getEndDate()

                                    updateList()
                                }
                                "5" -> {
                                    mBeginDate = getBeforeFirstDate()
                                    mEndDate = getBeforeEndDate()

                                    updateList()
                                }
                                "6" -> {
                                    mBeginDate = getYearFirstDate()
                                    mEndDate = getYearEndDate()

                                    updateList()
                                }
                                "7" -> {
                                    showTimeRangeDialog(
                                        isCurrentDate = true,
                                        isAfterLimited = true,
                                        onResult = { start, end ->
                                            getViewModel()
                                                .mUncheckTimeList
                                                .forEach { it.isChecked = false }

                                            getViewModel()
                                                .mUncheckTimeList
                                                .last()
                                                .isChecked = true

                                            mBeginDate = start
                                            mEndDate = end
                                            bean.name = "$mBeginDate ~ $mEndDate"
                                            timeHint.text = bean.name

                                            updateList()
                                        }
                                    )
                                }
                            }
                        }
                }
            }
    }

    /**
     * 押桶记录列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        // 押桶记录合计
        getViewModel()
            .handleTotal(
                keyWord = mKeyWord,
                beginDate = mBeginDate,
                endDate = mEndDate
            )

        // 押桶记录列表
        getViewModel()
            .handleList(
                page = index,
                keyWord = mKeyWord,
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = {
                    mList.apply {
                        if (index == 0) {
                            clear()
                            pageNum = 0
                        }
                        addItems(it)
                        it.notEmpty { pageNum++ }
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 列表数据刷新
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        if (mList.isNotEmpty()) {
            mList.clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}